package com.samphanie.dries;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.DataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

public abstract class AbsViewModel<T> extends ViewModel {

    private DataSource dataSource;
    private LiveData<PagedList<T>> pageData;
    private MutableLiveData<Boolean> mutableLiveData = new MutableLiveData<>();

    public AbsViewModel() {
        // 1.构建PagedList.Config对象,用以声明以何种方式分页
        PagedList.Config config = new PagedList.Config.Builder()
                .setPageSize(10)  // 指定每次分页加载的条目数量
                .setInitialLoadSizeHint(12) // 指定初始化数据加载的条目数量
                // .setPrefetchDistance(10) // 指定提前分页预加载的条目数量，默认和pageSize相等
                // .setMaxSize(100) // 指定数据源最大可加载的条目数量
                // .setEnablePlaceholders(false) // 指定未加载出来的条目是否用占位符替代,必须和setMaxSize搭配使用才有效
                .build();

        pageData = new LivePagedListBuilder(factory, config)
                .setInitialLoadKey(0)
                // .setFetchExecutor()
                .setBoundaryCallback(callback)
                .build();
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public LiveData<PagedList<T>> getPageData() {
        return pageData;
    }

    public MutableLiveData<Boolean> getMutableLiveData() {
        return mutableLiveData;
    }

    PagedList.BoundaryCallback<T> callback = new PagedList.BoundaryCallback<T>() {
        @Override
        public void onZeroItemsLoaded() {
            mutableLiveData.postValue(false);
        }

        @Override
        public void onItemAtFrontLoaded(@NonNull T itemAtFront) {
            mutableLiveData.postValue(true);
        }

        @Override
        public void onItemAtEndLoaded(@NonNull T itemAtEnd) {
            super.onItemAtEndLoaded(itemAtEnd);
        }
    };

    DataSource.Factory factory = new DataSource.Factory() {
        @NonNull
        @Override
        public DataSource create() {
            dataSource = createDataSource();
            return dataSource;
        }
    };

    public abstract DataSource createDataSource();

}
